import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { sendCodes,Authorizations } from '@/store/action/user'
import { useDispatch } from 'react-redux'
import { Toast } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useHistory, useLocation, } from 'react-router-dom'
export default function Login() {
type FormValues = {
    mobile: string
    code: string
}

const history = useHistory()
 // 🔔注意：useLocation 传入的泛型用于指定 state 对象格式
 const location = useLocation<{ from: string }>()
  const formik = useFormik({
      initialValues: {
        mobile: '13911111111',
        code: '123456',
        // mobile: '',
        // code: '',
      } as FormValues,
      onSubmit: async(values) => {
        console.log('当前表单的数据为', values)
        await dispatch(Authorizations(values))
        Toast.show({ content: '登陆成功' })
        // history.push('/')
        if (location.state) {
          // 替换成回跳的页面
          history.replace(location.state.from)
        } else {
          // 跳转到首页
          history.push('/home')
        }
      },
      // formik的表单验证
      // validate(values) {
      //     // 添加 TS 格式断言
      //     const errors = {} as FormValues
      //     console.log(23,errors);
      //     if (!/^1[3-9]\d{9}$/.test(values.mobile)) {
      //       errors.mobile = '手机号格式错误'
      //     }
      //     if (!/^\d{6}$/.test(values.code)) {
      //       errors.code = '验证码格式错误'
      //     }
      //     return errors
      //   },
      // Yup 表单校验
      validationSchema: Yup.object().shape({
        // 手机号校验
        mobile: Yup.string().required('必填项').matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
        // 验证码校验
        code: Yup.string().required('必填项').matches(/^\d{6}$/, '验证码格式错误'),
      })
    })
    const dispatch = useDispatch()
    const [time, setTime] = useState(0)
    const timerId = useRef(-1)
    const handleSendCodes=async()=>{
        // 校验错误
        if (formik.errors.mobile) return Toast.show({ content: formik.errors.mobile })
         // 调用发送验证码
        await dispatch(sendCodes(formik.values.mobile))
        // 成功提示
         Toast.show({ content: '获取验证码成功', duration: 1000 })
         // 开启倒计时
         setTime(60)
        //  let timerId = setInterval(() => {
          timerId.current = window.setInterval(() => {
            // 💥当我们每次都想要获取到最新的状态，需要写成 箭头函数的形式
            // 🔔 箭头函数写法：每次都可获取到最新的状态
            setTime((time) => {
              // if (time === 1) clearInterval(timerId)
              if (time === 1) clearInterval(timerId.current)
              return time - 1
            })
          }, 1000)
    }
    useEffect(() => {
        // 清理函数
        return () => {
          // 组件卸载清理定时器，避免内存泄漏
          clearInterval(timerId.current)
        }
      }, [])
  return (
    <div className={styles.root}>
        <NavBar>登录</NavBar>
      <div className='content'>
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <div className='input-item'>
          <Input
              autoFocus
              className='input'
              placeholder='请输入手机号'
              autoComplete='off'
              type='text'
              name='mobile'
              maxLength={11}
              errorMsg={formik.touched.mobile ? formik.errors.mobile : ''}
              onBlur={formik.handleBlur}
              value={formik.values.mobile}
             onChange={formik.handleChange}
            />
          </div>

          {/* 短信验证码输入框 */}
          <div className='input-item'>
          <Input
              className='input'
              placeholder='请输入验证码'
              autoComplete='off'
              type='text'
              name='code'
              maxLength={6}
              errorMsg={formik.touched.code ? formik.errors.code : ''}
              onBlur={formik.handleBlur}
              extra={<span onClick={() => handleSendCodes()}>{time === 0 ? '获取验证码' : `${time}秒后重试`}</span>}
              value={formik.values.code}
              onChange={formik.handleChange}
            />
          </div>

          {/* 登录按钮 */}
          {/* <button type='submit' className='login-btn' disabled={false}>
            登录
          </button> */}
          <button type='submit' className='login-btn' disabled={!formik.isValid}>登录</button>
        </form>
      </div>
    </div>
  )
}

